<template>
  <div class="w-pie-chart"></div>
</template>

<script type='text/babel'>
  import $ from 'jquery'
  import WCommons from '../../../../static/js/wanba.commons'
  import ChartMixins from './ChartMixins'

  var _resolveDatas = function (component) {
    var a = component.chartAdapter
    var result = []
    var datas = a.seriesDatas()
    if ($.isArray(datas)) {
      var selected = component.selectedItem
      datas.forEach(function (item, index) {
        if (selected === index) {
          result.push({
            name: item.label,
            y: item.value,
            sliced: true,
            selected: true
          })
        } else {
          result.push([item.label, item.value])
        }
      })
    }
    return result
  }

  export default {
    mixins: [ChartMixins],
    props: {
      selectedItem: {
        type: Number,
        default: -1
      },
      tooltipLabel: {
        type: String,
        default: ''
      },
      tooltipFormat: {
        type: String,
        default: '<b>{point.y}</b>:{point.percentage:.1f}%'
      }
    },
    created: function () {
      var self = this
      WCommons.extends(self.chartAdapter, {
        seriesDatas: function () {
          throw new Error('adapter的seriesData()方法未实现')
        }
      })
    },
    resolveDatasetChanged: function () {
      var self = this
      self.$options.chart.series[0].setData(_resolveDatas(self))
    },
    preConfigChartOptions: function () {
      var self = this
      return {
        chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          width: self.chartWidth,
          height: self.chartHeight
        },
        title: {
          text: self.chartTitle
        },
        legend: {
          enabled: false
        },
        credits: {
          enabled: false
        },
        tooltip: {
          pointFormat: self.tooltipLabel + self.tooltipFormat
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        },
        series: [{
          type: 'pie',
          name: '',
          data: (function () {
            return _resolveDatas(self)
          })()
        }]
      }
    }
  }
</script>

<style>
  .pie-chart, .pie-chart svg {
    overflow: visible;
  }
</style>
